package com.zhentao.filter;

import com.zhentao.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response= exchange.getResponse();

        //1.如果是放行的请求，直接放行  比如说登录
        if(request.getURI().getPath().contains("login")){
            return chain.filter(exchange);
        }

        //2.获取token   -header
        String token= request.getHeaders().getFirst("token");
        if(token==null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//401
            return  response.setComplete();
        }

        //3.判断token是否正确
        try {
            //解密成功
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //查询出id
            Integer userId = (Integer) claims.get("id");
            System.err.println("解密查询id"+userId);
            //怎么把它传递到各个微服务里面呢
            //把userId放到header里面去传递
            ServerHttpRequest serverHttpRequest= request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId",userId+"");
            }).build();
            //重置请求 request
            exchange.mutate().request(serverHttpRequest).build();

        }catch (Exception e){
            //解密失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
